const globalIp = getApp().globalData.userIp
const XLSX = require('../../xlsx.mini.min.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#3cc51f",
    // filePath: "",
    list: [{
      pagePath: "/template/company/addorder/addorder",
      iconPath: "/images/cailiao/addC.png",
      selectedIconPath: "/images/cailiao/addO.png",
      text: "新增订单"
    }, 
    {
      pagePath: "/template/company/addorder/addorderrecord/addorderrecord",
      iconPath: "/images/cailiao/recordC.png",
      selectedIconPath: "/images/cailiao/recordO.png",
      text: "提交记录"
    }],
    arrayLineStatus: ['样品', '成品'],
    indexLineStatus: 0,
    CardCode: '',
    CardName: '',
    dateTime: '',
    CusOdNum: '',
    DocStatus: '',
    detail: []
    // indexLineStatus: wx.getStorageSync('indexLineStatus') || 0,
    // dateTime: wx.getStorageSync('indexLineStatus') || '',
    // CusOdNum: wx.getStorageSync('CusOdNum') || '',
    // DocStatus: wx.getStorageSync('DocStatus') || '',
    // detail: wx.getStorageSync('detail') || []
  },

  bindChange: function(e) {
    this.setData({
      indexLineStatus: e.detail.value
    })
    wx.setStorageSync('indexLineStatus', e.detail.value);
  },

  changeDate(e) {
    let value = e.detail.value.replaceAll('-','.')
    this.setData({
      dateTime: value
    })
    wx.setStorageSync('dateTime', value);
  },

  inputchange(e) {
    if (e.currentTarget.dataset.name === 'CusOdNum') {
      this.setData({
        CusOdNum: e.detail.value
      })
      wx.setStorageSync('CusOdNum', e.detail.value);
    } else if (e.currentTarget.dataset.name === 'DocStatus') {
      this.setData({
        DocStatus: e.detail.value
      })
      wx.setStorageSync('DocStatus', e.detail.value);
    }
  },

  excelOut() {
    // let that = this;
    wx.downloadFile({
      url: globalIp + 'upLoadImg/file/InstanceFile.xlsx',
      filePath: wx.env.USER_DATA_PATH + '/' + 'InstanceFile.xlsx', // 本地自定义的文件名
      success: function (res) {
        let data = res.filePath;
        wx.openDocument({
          filePath: data,
          fileType: 'xlsx',
          showMenu: true,  //表示右上角是否有转发按钮
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function (res) {
            console.log(res)
          }
        })
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },

  excelIn() {
    let that = this;
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['.xlsx', '.xls', '.XLSX', '.XLS', 'xlsx', 'xls', 'XLSX', 'XLS'],
      success: res => {
        try {
          const path = res.tempFiles[0].path
          const fs = wx.getFileSystemManager()
          const data = fs.readFileSync(path, 'binary') // data为binary数据
          let workbook = XLSX.read(data, {
            type: "binary"
          });
          const sheetName = workbook.SheetNames[0]
          let sheet = workbook.Sheets[sheetName]
          const options = {
            raw: false // 如果不加raw:true的话日期会被读成数字，根据开发需求决定
          }
          const rawData = XLSX.utils.sheet_to_json(sheet, options);
          
          let detail = wx.getStorageSync('detail') || []
          for (var i = 0; i < rawData.length; i++) {
            // 验证数据
            let ItemName = rawData[i].品名
            let Length = rawData[i].长度
            let Height = rawData[i].厚度
            let Width = rawData[i].宽度
            let CusItemCode = rawData[i].客户料号
            let Quantity = rawData[i].数量
            let Remark = rawData[i].备注
            if (ItemName == "" || Length == "" || Height == "" || Width == "" || Quantity == "") {
              continue;
            }
            if (ItemName.length < 3 || Width < 10 || Length < 100 || Quantity < 1) {
              continue;
            }
            let row = {}
            row.itemName = ItemName
            row.length = Length
            row.height = Height
            row.width = Width
            row.cusItemCode = CusItemCode
            row.quantity = Quantity
            row.remark = Remark
            row.lineNum = Object.keys(detail).length > 0 ? wx.getStorageSync('maxLine') + 1 : 1
            detail.push(row)
            wx.setStorageSync('maxLine', row.lineNum)
            wx.setStorageSync('detail', detail)
          }
          that.setData({
            detail: wx.getStorageSync('detail')
          })
        } catch (e) {
          console.error(e)
          wx.showModal({
            title: '提示',
            content: "文件读取失败",
            showCancel: false
          })
          return
        }
      },
      fail: res => {
        console.log(res, 'fail')
      }
    })    
  },

  excelInPC(e) {
    const deviceInfo = wx.getDeviceInfo()
    if (deviceInfo.platform === 'android' || deviceInfo.platform === 'ios') {
      wx.showToast({
        title: '手机端禁止跳转！',
        icon: 'error',
        duration: 2000 //持续的时间
      })
    } else {
      wx.navigateTo({
        url: '/template/company/addorder/uploadexcel/uploadexcel?openid='+wx.getStorageSync('userInfo').openid,
      })
    }
  },

  addLine() {
    wx.navigateTo({
      url: './addorderdetail/addorderdetail',
    })
    // let detail = wx.getStorageSync('detail') || []
    // let row = {}
    // row.ItemName = 'UN3-0353'
    // row.Length = '170'
    // row.Height = '1400'
    // row.Width = '6'
    // row.CusItemCode = '1'
    // row.Quantity = '6.0'
    // row.Remark = '5-11'
    // detail.push(row)
    // wx.setStorageSync('detail', detail)
    // this.setData({
    //   detail: wx.getStorageSync('detail')
    // })
  },

  switchTab(e) {
    const data = e.currentTarget.dataset
    const url = data.path
    wx.redirectTo({url})
    // this.setData({
    //   selected: data.index
    // }) 
  },

  submit() {
    var that = this;
    if (that.data.dateTime == "") {
      wx.showToast({
        title: "请填写带*号必填项~",
        icon: "none",
      });
      return false;
    }
    if (!wx.getStorageSync('detail') || wx.getStorageSync('detail') == "") {
      wx.showToast({
        title: "请添加条目后提交~",
        icon: "none",
      });
      return false;
    }
    wx.request({
      url: globalIp + 'home/ordr/xcxOrderVer1', 
      data: {
        code: that.data.CusOdNum,
        sdate: that.data.dateTime,
        realName: that.data.DocStatus,
        value: "1",
        openId: wx.getStorageSync('userInfo').openid || '',
        details: wx.getStorageSync('detail')
      },
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      success: function(res) {
        if (res.data.success) {
          wx.removeStorageSync('indexLineStatus')
          wx.removeStorageSync('dateTime')
          wx.removeStorageSync('CusOdNum')
          wx.removeStorageSync('DocStatus')
          wx.removeStorageSync('detail')
          wx.removeStorageSync('maxLine')
          wx.removeStorageSync('oldRow')
          wx.showToast({
            title: res.data.msg,
            icon: 'success',
            duration: 2000,
            success: function(e) {
              // 弹出弹窗提示是否提醒
              wx.showModal({
                title: '转单审核提醒',
                content: '下单成功，是否开启转单成功提醒？',
                success: function (sm) {
                  if (sm.confirm) {
                    that.openPopup();
                  }
                  // 点击按钮后再跳转
                  wx.navigateTo({
                    url: './addorderrecord/addorderrecord',
                  }) 
                }
              })
              // setTimeout(() => {
                
              // }, 1000)
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },

  updateSO(e) {
    let item = JSON.stringify(e.currentTarget.dataset.item)
    wx.navigateTo({
      url: './addorderdetail/addorderdetail?item=' + item,
    })
  },

  deleteSO(e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          let item = e.currentTarget.dataset.item
          let detail = wx.getStorageSync('detail')
          const index = detail.findIndex((d) => JSON.stringify(d) === JSON.stringify(item));
          if (index !== -1) {
            detail.splice(index, 1);
            wx.setStorageSync('detail', detail);
            that.onShow();
          }
        } 
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // let that = this;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      indexLineStatus: wx.getStorageSync('indexLineStatus') || 0,
      dateTime: wx.getStorageSync('dateTime'),
      CusOdNum: wx.getStorageSync('CusOdNum'),
      DocStatus: wx.getStorageSync('DocStatus'),
      detail: wx.getStorageSync('detail'),
      CardCode: wx.getStorageSync('userInfo').CardCode,
      CardName: wx.getStorageSync('userInfo').userName
    })
  },

  // 是否设置过授权
  openPopup() {
    var tempId = ['siECsejH-Mp0jfhuH9NY-f2CSj87YeD_4wRXgTO9HiY'] // 用户同意的消息模板id
    wx.requestSubscribeMessage({   // 调起消息订阅界面
      tmplIds: tempId,
      success (res) {
        console.log(res)
        if (res[tempId[0]] === 'accept') {
          // 这里是获取下发权限地方，根据官方文档，可以根据  wx.getSetting() 的 withSubscriptions   这个参数获取用户是否打开订阅消息总开关。后面我们需要获取用户是否同意总是同意消息推送。所以这里要给它设置为true 。
          wx.getSetting({
            withSubscriptions: true,   //  这里设置为true,下面才会返回mainSwitch
            success: function(res){  
              // 调起授权界面弹窗
              if (res.subscriptionsSetting.mainSwitch) {  // 用户打开了订阅消息总开关
                if (res.subscriptionsSetting.itemSettings != null) {   // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
                  let moIdState = res.subscriptionsSetting.itemSettings[tempId];  // 用户同意的消息模板id
                  if (moIdState === 'accept'){   
                    console.log("用户选择了“保持以上选择”")
                  }
                }
              } else {
                console.log('订阅消息未开启')
              }      
            }
          })
        }
        else if (res[tempId[0]] === 'reject') {
          console.log('用户拒绝推送')
        }
      },
      fail (err){
        if (err.errCode == 20004) {
          console.log('关闭小程序主开关')
        } else {
          console.log('订阅失败')
        }
      }
    })
  },

})